class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        Set<String> hash=new HashSet<>();
        for(String x:wordList) hash.add(x);
        Set<String> vis=new HashSet<>();
        Queue<String> q=new LinkedList<>();
        vis.add(beginWord);
        q.add(beginWord);
        if(!hash.contains(endWord)) return 0;
        int ret=1;
        while(!q.isEmpty()){
            int sz=q.size();
            ret++;
            while(sz--!=0){
                String t=q.poll();
                for(int i=0;i<t.length();i++){
                    char[] tmp=t.toCharArray();
                    for(char ch='a';ch<='z';ch++){
                        tmp[i]=ch;
                        String next=new String(tmp);
                        if(hash.contains(next)&&!vis.contains(next)){
                            if(next.equals(endWord))return ret;
                            q.add(next);
                            vis.add(next);
                        }
                    }
                }
            }
        }  
        return 0;
    }
}